<template>
  <div class="page-main" v-title data-title="报工单详情">
    <home-nav :userData="userinfo"></home-nav>
    <div class="container">
      <div class="head-content">
        <span class="bold-font">报工单详情</span>
        <ul>
          <!-- <li v-if="
            task.currentHandlerUser == '1' ||
            checkPermission(['WORK_REPORT_MANAGER', 'WORK_REPORT_ACCEPTER', '合同报工参与人'])
          " :class="{ active: visiblePayment }">
            <span class="iconfont icon-faqi"></span>
            <a-popover placement="bottom" v-model="visiblePayment" trigger="click">
              <a slot="content" class="cr-content-pop">
                <p v-if="
                  task.currentHandlerUser == '1' || checkPermission(['WORK_REPORT_MANAGER', 'WORK_REPORT_ACCEPTER'])
                " @click="createAccept()">
                  发起验收付款
                </p>
                <p @click="openAcceptList()">查看记录</p>
              </a>
              <span>验收付款</span>
            </a-popover>
          </li> -->
          <li
            v-if="
              task.currentHandlerUser == '1' ||
              checkPermission(['WORK_REPORT_MANAGER', 'WORK_REPORT_ACCEPTER', '合同报工参与人'])
            "
            @click="openAcceptList()"
          >
            <span class="iconfont icon-faqi"></span>验收付款
          </li>

          <!-- <li v-if="
            task.currentHandlerUser == '1' ||
            checkPermission(['WORK_REPORT_MANAGER', 'WORK_REPORT_ACCEPTER', '合同报工参与人'])
          " :class="{ active: visibleQuality }">
            <span class="iconfont icon-zhihang"></span>
            <a-popover placement="bottom" v-model="visibleQuality" trigger="click">
              <a slot="content" class="cr-content-pop">
                <p v-if="
                  task.currentHandlerUser == '1' || checkPermission(['WORK_REPORT_MANAGER', 'WORK_REPORT_ACCEPTER'])
                " @click="createQuality()">
                  发起质量通知单
                </p>
                <p @click="openQualityList()">查看记录</p>
              </a>
              <span>质量通知单</span>
            </a-popover>
          </li> -->
          <li
            v-if="
              task.currentHandlerUser == '1' ||
              checkPermission(['WORK_REPORT_MANAGER', 'WORK_REPORT_ACCEPTER', '合同报工参与人'])
            "
            @click="openQualityList()"
          >
            <span class="iconfont icon-faqi"></span>质量通知单
          </li>
          <li
            v-if="
              task.currentHandlerUser == '1' ||
              checkPermission(['WORK_REPORT_MANAGER', 'WORK_REPORT_ACCEPTER', '合同报工参与人'])
            "
            @click="toExecute()"
          >
            <span class="iconfont icon-shenpi1"></span>合同信息
          </li>
          <li
            v-if="
              task.currentHandlerUser == '1' ||
              checkPermission(['WORK_REPORT_MANAGER'], 'WORK_REPORT_ACCEPTER', '合同报工参与人')
            "
            @click="toContractAttach()"
          >
            <a-icon type="link" />合同附件
          </li>
          <li
            v-if="task.currentHandlerUser == '1' || checkPermission(['WORK_REPORT_MANAGER'])"
            @click="openSettlementDetail()"
          >
            <span class="iconfont icon-kecheng"></span>核算表
          </li>
          <li @click="toTaskLog()"><span class="iconfont icon-wendang"></span>报工日志</li>
          <li>
            <span class="iconfont icon-faqi"></span>
            <a-popover placement="bottom" trigger="click">
              <a slot="content" class="cr-content-pop">
                <p @click="toPsCreateConstructNotice()">发起施工通知单</p>
                <p @click="toPsShowCreateConstructNoticeList()">查看记录</p>
              </a>
              <span>施工通知</span>
            </a-popover>
          </li>
        </ul>
        <div class="btn-line">
          <a-button
            v-if="
              (task.currentHandlerUser == '1' || checkPermission(['WORK_REPORT_MANAGER'])) &&
              (!task.partaIsCancleSubmit || task.partaIsCancleSubmit == '0' || task.partaIsCancleSubmit == '-1')
            "
            @click="handleSave"
            class="hte-btn add-btn"
            type="primary"
            >保存</a-button
          >
          <a-button
            v-if="checkPermission(['WORK_REPORT_MANAGER']) && task.partaIsCancleSubmit == '1'"
            @click="handleCancel"
            class="hte-btn"
            >取消</a-button
          >
        </div>
      </div>
      <div class="content">
        <a-form-model ref="ruleForm">
          <section>
            <div class="section-header">报工单信息</div>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="报工单编号：">
                  <a-input
                    disabled
                    :value="
                      project.busKey && project.itemCount
                        ? project.busKey + '(' + task.itemIndex + '/' + project.itemCount + ')'
                        : ''
                    "
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="报工类别：">
                  <a-select disabled default-value="0" style="width: 100%">
                    <a-select-option v-for="(code, index) in codes.WorkReportType" :key="index" :value="code.code">
                      {{ code.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="报工状态：">
                  <a-select disabled v-model="task.status">
                    <a-select-option
                      v-for="(code, index) in codes.WorkReportTaskStatus"
                      :value="code.code"
                      :key="index"
                    >
                      {{ code.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="合同编号：">
                  <a-input disabled v-model="project.contractNumber" />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="合同名称：">
                  <a-input disabled v-model="project.contractName" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="项目负责人：">
                  <UserInputSelector
                    :username.sync="task.handlerUserId"
                    :realname.sync="task.handlerUser"
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
                    multiple="default"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item label="供应商名称">
                  <a-input disabled v-model="project.supplierName" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="合同金额：">
                  <a-input disabled v-model="project.amount" />
                </a-form-model-item>
              </a-col>
              <a-col :span="16">
                <a-form-model-item ref="nodeContent" label="工期节点内容：" prop="nodeContent">
                  <a-input :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" v-model="task.nodeContent" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="关联节点金额：">
                  <a-input :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" v-model="task.paymentAmount" />
                </a-form-model-item>
              </a-col>

              <a-col :span="16">
                <a-form-model-item label="付款节点内容：" prop="paymentContent">
                  <a-input :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" v-model="task.paymentContent" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="PO单行号：">
                  <a-input
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
                    v-model="task.poLine"
                    :suffix="'共' + (project.poLineCount ? project.poLineCount : '0') + '行'"
                  />
                </a-form-model-item>
              </a-col>

              <a-col :span="8">
                <a-form-model-item label="费用支出号">
                  <a-input
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
                    placeholder="自动带入"
                    v-model="task.costNumber"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="提交资料内容：">
                  <a-input :disabled="!checkPermission(['WORK_REPORT_MANAGER'])" v-model="task.submitResource" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col :span="8">
                <a-form-model-item label="合同约定日期：">
                  <a-date-picker
                    :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
                    style="width: 100%"
                    valueFormat="YYYY-MM-DD"
                    v-model="task.complateTime"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="报工节点标志：">
                  <div style="display: flex; justify-content: space-around">
                    <a-select
                      :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
                      v-model="task.nodeIdentify"
                      style="width: 100%"
                    >
                      <a-select-option v-for="(code, index) in contractNodeOptions" :key="index" :value="code">
                        {{ code }}
                      </a-select-option>
                    </a-select>
                    <div style="display: flex; width: 20vw; justify-content: flex-end">
                      <span style="min-width: 60px; text-align: right; padding-right: 5px; line-height: 40px"
                        >税率:</span
                      >
                      <a-input
                        placeholder=""
                        v-model="task.taxRate"
                        :disabled="!checkPermission(['WORK_REPORT_MANAGER'])"
                        :suffix="'%'"
                      />
                    </div>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="付款节点标志：">
                  <div style="display: flex; justify-content: space-around">
                    <a-select v-model="task.isPayNode" style="width: 100%" disabled>
                      <a-select-option v-for="(code, index) in yesOrNo" :key="index" :value="code.code">
                        {{ code.name }}
                      </a-select-option>
                    </a-select>
                    <div style="display: flex; width: 60vw; justify-content: flex-end">
                      <span style="min-width: 110px; text-align: right; padding-right: 5px; line-height: 40px"
                        >多个付款条件:</span
                      >
                      <a-select v-model="task.isMutiContiditon" style="width: 100%" disabled>
                        <a-select-option v-for="(code, index) in yesOrNo" :key="index" :value="code.code">
                          {{ code.name }}
                        </a-select-option>
                      </a-select>
                    </div>
                  </div>
                </a-form-model-item>
              </a-col>
            </a-row>
          </section>
          <ResultABox
            :project="project"
            :task.sync="task"
            :permission="permission"
            type="0"
            :currentHandlerUser="task.currentHandlerUser"
            ref="resultABoxRef"
          />
          <ResultBBox :project="project" :task.sync="task" :permission="permission" type="1" ref="resultBBoxRef" />
        </a-form-model>
      </div>
    </div>
    <PaymentList
      :show="showPaymentList"
      :taskId="taskId"
      :permission="permission"
      @hide="closeAcceptList"
      @createAccept="createAccept"
    />
    <QualityList
      :show="showQualityList"
      :permission="permission"
      :poNo="project.busKey"
      @hide="closeQualityList"
      @createQuality="createQuality"
    />
    <SettlementDetail
      :show="showSettlementDetail"
      :supplierCode="project.supplierCode"
      :wbs="task.costNumber"
      :taskInfoId="task.id"
      @close="closeSettlementDetail"
      :edit="true"
    />
    <UserSelector :show="showUserSelector" :muti="false" @selected="selectUser" />
    <dataChangeTimeLine ref="dataChangeTimeLine" />
  </div>
</template>
<script>
import { getAction, postAction } from '@/api/manage'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Modal } from 'ant-design-vue'
export default {
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    ResultABox: () => import('@/views/workReport/task/ResultA'),
    ResultBBox: () => import('@/views/workReport/task/ResultB'),
    PaymentList: () => import('@/views/workReport/task/TaskDetail_PaymentList'),
    QualityList: () => import('@/views/workReport/task/TaskDetail_QualityList'),
    SettlementDetail: () => import('@/views/workReport/util/SettlementDetail'),
    UserSelector: () => import('@/views/workReport/role/UserSelector'),
    dataChangeTimeLine: () => import('@/views/dataChange/dataChangeTimeLine'),
  },
  data() {
    return {
      dataTitle: this.$route ? this.$route.name : '',
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'ContractReportInfo',
      },
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      taskId: this.$route.params && this.$route.params.taskId,
      project: {},
      task: {},
      urls: {
        project: '/workReport/project/info',
        item: '/workReport/task/info',
        edit: '/workReport/task/edit',
        cancel: '/workReport/task/cancel',
        codes: '/manage/codeInfo/queryByTypes',
        psCodes: '/hte/contract/codes',
        myPermission: '/workReport/project/myPermission',
        newPayment: '/workReport/payment/newPayment',
        paymentList: '/workReport/payment/page',
        personList: '/person/info/personList',
      },
      yesOrNo: [
        { code: 1, name: '是' },
        { code: 0, name: '否' },
      ],
      result: {},
      codes: {},
      showUserSelector: false,
      contractNodeOptions: ['到货', '安装', '验收', '质保'],
      permission: [],
      showPaymentList: false,
      visiblePayment: false,
      showQualityList: false,
      visibleQuality: false,
      showSettlementDetail: false,
      personMap: [],
      existPersonMap: [],
      personList: [],
      selectUserTimeOut: null,
      selectUserKeyWord: null,
    }
  },
  mounted() {
    this.fetchTask()
    this.fetchCodes()
    this.fetchPsCodes()
  },
  methods: {
    fetchPermission() {
      getAction(this.urls.myPermission, { projectId: this.task.projectId }).then((res) => {
        if (res.success) {
          this.permission = res.result
        }
      })
    },
    checkPermission(powers) {
      let hasPower = false
      for (let p of powers) {
        if (this.permission.indexOf(p) > -1) {
          hasPower = true
          break
        }
      }
      return hasPower
    },
    fetchPsCodes() {
      postAction(this.urls.psCodes, { codes: ['contract_status'] }).then((res) => {
        if (res.success) {
          this.codes = { ...this.codes, ...res.result }
        }
      })
    },
    fetchCodes() {
      getAction(this.urls.codes, { types: 'WorkReportTaskStatus,WorkReportType,WorkReportTaskPaymentStatus' }).then(
        (res) => {
          if (res.success) {
            this.codes = { ...this.codes, ...res.result }
          }
        }
      )
    },
    fetchProject() {
      this.project = {}
      getAction(this.urls.project + '/' + this.task.projectId, {}).then((res) => {
        if (res.success) {
          this.project = res.result
        }
      })
    },
    fetchTask() {
      getAction(this.urls.item + '/' + this.taskId, {}).then((res) => {
        if (res.success) {
          if (this.userinfo.info.username == res.result.handlerUserId) {
            this.$set(this.task, 'currentHandlerUser', '1')
          } else {
            this.$set(this.task, 'currentHandlerUser', '0')
          }
          this.task = res.result
          this.fetchProject()
          this.fetchPermission()
        }
      })
    },
    handleSave() {
      let type = 0
      let params = {}
      let attachs = this.$refs.resultABoxRef.getAttach()
      if (!this.task.complateTime) {
        return this.$messageWorkReport.warning('请输入合同约定时间')
      }
      /**
       * 1、系统保存时，提醒检测缺漏项
       * A、【节点报工】=“已完成”&【实际完成日期】，两个需要一起填；
       * B、【节点报工】=“质量合格”&【现场验收日期】，两个需要一起填；
       * 如果填了B的内容，保存时要检测到必须要填A的内容。
       */
      if (
        (this.task.partaStatus == '2' && !this.task.partaActualTime) ||
        (this.task.partaStatus != 2 && this.task.partaActualTime)
      ) {
        return this.$messageWorkReport.warning(
          '【节点报工】为“已完成”,【实际完成日期】必填 或 已填写【实际完成日期】,【节点报工】必须为“已完成”'
        )
      }
      if (
        (this.task.partaResult == '质量合格' && !this.task.partaAcceptTime) ||
        (this.task.partaResult != '质量合格' && this.task.partaAcceptTime)
      ) {
        return this.$messageWorkReport.warning(
          '【节点报工】＝“质量合格”时,必须填写【现场验收日期】 或 已填写【现场验收日期】时,【节点报工】必须为“质量合格”'
        )
      } else {
        var acceptTime = new Date(this.task.partaActualTime).getTime()
        var actualTime = new Date(this.task.partaActualTime).getTime()
        if (acceptTime < actualTime) {
          return this.$messageWorkReport.warning('现场验收时间必须晚于或等于实际完成时间')
        }
      }
      /////////////////////////////////////////////
      /**
       * 当【工期状态】=逾期，需要填写【逾期责任方】、【逾期具体原因】【补充说明】
       */
      if (this.task.partaNodeStatus == '逾期') {
        if (!this.task.partaDelayReason || !this.task.partaDelayRemark || !this.task.partaRemark) {
          return this.$messageWorkReport.warning(
            '【工期状态】=“逾期”，【逾期责任方】、【逾期具体原因】、【补充说明】为必填项。'
          )
        }
        if (this.task.partaStatus != '2' && !this.task.partaPlanTime) {
          return this.$messageWorkReport.warning('【工期状态】=“正常”，需要填写【预计完成日期】为必填项')
        }
      } else {
        if (this.task.partaStatus != '2' && this.task.partaPlanTime) {
          if (!this.task.partaDelayReason || !this.task.partaDelayRemark || !this.task.partaRemark) {
            return this.$messageWorkReport.warning(
              '【工期状态】=“正常”，【预计完成日期】≠“空白”时，【逾期责任方】、【逾期具体原因】、【补充说明】为必填项。'
            )
          }
        } else {
          this.$set(this.task, 'partaDelayReason', '')
          this.$set(this.task, 'partaDelayRemark', '')
        }
      }
      if (this.task.partaStatus == '2' && this.task.partaResult == '质量合格') {
        type = 1
        if (this.task.nodeIdentify == '验收' || this.task.isPayNode == '1') {
          if (this.task.partaBudgetingUser) {
            if (!attachs || attachs.length <= 0) {
              return this.$messageWorkReport.warning('基建类合同请上传合同报工确认的相关佐证材料')
            }
          } else {
            if (attachs && attachs.length > 0) {
              let hasAcceptFile = false
              attachs.forEach((attach) => {
                if (attach.fileName && attach.fileName.indexOf('验收') > -1) {
                  hasAcceptFile = true
                }
              })
              if (!hasAcceptFile) {
                return this.$messageWorkReport.warning(
                  '请上传含“验收”二字的签名文件；基建类合同请填写造价员名字及上传合同报工确认的相关佐证材料'
                )
              }
            } else {
              return this.$messageWorkReport.warning(
                '请上传含“验收”二字的签名文件；基建类合同请填写造价员名字及上传合同报工确认的相关佐证材料'
              )
            }
          }
        }
      }
      this.task.partaIsCancleSubmit = type
      postAction(this.urls.edit, this.task).then((res) => {
        if (res.success) {
          this.$messageWorkReport.success('保存成功')
          this.fetchTask()
          if (this.task.partaDelayReason == '1') {
            //乙方责任则需要提醒报工人是否创建质量通知单
            this.autoCreateQuality()
          }
          this.autoCreateAccept(type)
        } else {
          this.$messageWorkReport.error('保存失败:' + res.message)
        }
      })
    },
    handleCancel() {
      getAction(this.urls.cancel, { id: this.taskId, type: 0 }).then((res) => {
        if (res.success) {
          this.$messageWorkReport.success('取消成功')
          this.fetchTask()
        } else {
          this.$messageWorkReport.error('取消失败')
        }
      })
    },
    openAcceptList() {
      this.visiblePayment = false
      this.showPaymentList = true
    },
    closeAcceptList() {
      this.visiblePayment = false
      this.showPaymentList = false
    },
    async createAccept() {
      if (this.task.partaIsCancleSubmit != '1') {
        return this.$messageWorkReport.error('请先提交报工单')
      }
      if (this.task.isPayNode != '1') {
        if (!this.task.nodeIdentify) {
          return this.$messageWorkReport.error('工期节点标识为空,且非付款节点,请勿发起验收付款')
        } else if (this.task.nodeIdentify != '验收') {
          return this.$messageWorkReport.error('本任务不涉及验收付款，无需发起流程。')
        }
      }
      let param = {}
        param.taskId = this.taskId
      let res = await postAction(this.urls.paymentList, param)
      let records = res.result.records
      let auditingOrPassed = 0
      let auditId = null
      let rejected = 0
      let creating = 0
      let creatingId = null
      records.forEach((r) => {
        if (['1', '2'].indexOf(r.status) > -1) {
          auditingOrPassed++
          auditId = r.id
        } else if (['3'].indexOf(r.status) > -1) {
          rejected++
        } else {
          creating++
          creatingId = r.id
        }
      })
      //在原来的提醒的基础上增加检测：
      //如果已生成的公文状态有在审批中或者是审批通过的，不需要弹出提醒。
      //如果已生成的公文状态只是审批不通过，则直接生成公文。
      if (creating <= 0) {
        this.newPayment()
      } else {
        this.windowOpen('/workReport/editPayment/' + creatingId)
      }
    },
    autoCreateQuality() {
      let content = '逾期责任方为乙方责任，请确认是否需要生成质量通知单'
      let that = this
      Modal.confirm({
        title: '提醒',
        content: content,
        onOk() {
          that.windowOpen('/workReport/addQuality/' + that.task.id)
        },
        onCancel() {},
      })
    },
    async autoCreateAccept(type) {
      if (type == 1) {
        if (this.task.isPayNode != '1') {
          if (this.task.nodeIdentify != '验收') {
            return false
          }
        }
        let that = this
        let param = {}
        param.taskId = this.taskId
        let res = await postAction(this.urls.paymentList, param)
        let records = res.result.records
        let auditing = 0
        let auditId = null
        let rejected = 0
        let creating = 0
        let creatingId = null
        records.forEach((r) => {
          if (['1'].indexOf(r.status) > -1) {
            auditing++
            auditId = r.id
          } else if (['3'].indexOf(r.status) > -1) {
            rejected++
          } else {
            creating++
            creatingId = r.id
          }
        })
        //在原来的提醒的基础上增加检测：
        //如果已生成的公文状态有在审批中或者是审批通过的，不需要弹出提醒。
        //如果已生成的公文状态只是审批不通过，则直接生成公文。

        if (auditing > 0) {
          this.windowOpen('/workReport/editPayment/' + auditId)
          return
        }
        if (creating <= 0) {
          this.newPayment()
        } else {
          this.windowOpen('/workReport/editPayment/' + creatingId)
        }
        // let content = '已生成公文,是否重新生成公文'
        // if (total == 0) {
        //   content = '发起合同验收付款审批表'
        // }
        // Modal.confirm({
        //   title: '提醒',
        //   content: content,
        //   onOk() {},
        //   onCancel() {},
        // })
      }
      if (type == 0 && this.task.partaStatus == '2' && this.task.partaResult != '质量合格') {
        this.$warning({
          title: '提醒',
          content: '请于5个工作日内组织验收并填写是否合格',
        })
      }
    },
    newPayment() {
      getAction(this.urls.newPayment, { taskId: this.taskId }).then((res) => {
        if (res.success) {
          this.windowOpen('/workReport/editPayment/' + res.result.id)
        } else {
          this.$messageWorkReport.error('发起合同验收付款审批表错误:' + res.message)
          this.openAcceptList()
        }
      })
    },
    openQualityList() {
      this.visibleQuality = false
      this.showQualityList = true
    },
    closeQualityList() {
      this.visibleQuality = false
      this.showQualityList = false
    },
    toPsCreateConstructNotice() {
      console.info(
        process.env.VUE_APP_HLPS_WEB_BASE_URL +
          '/' +
          'tpLogin?token=' +
          this.$ls.get(ACCESS_TOKEN) +
          '&tp=hs&redirect=' +
          encodeURIComponent('/constructNotice/add/1?busKey=' + this.project.busKey)
      )
      window.open(
        process.env.VUE_APP_HLPS_WEB_BASE_URL +
          '/' +
          'tpLogin?token=' +
          this.$ls.get(ACCESS_TOKEN) +
          '&tp=hs&redirect=' +
          encodeURIComponent('/constructNotice/add/1?busKey=' + this.project.busKey)
      )
    },
    toPsShowCreateConstructNoticeList() {
      window.open(
        process.env.VUE_APP_HLPS_WEB_BASE_URL +
          '/' +
          'tpLogin?token=' +
          this.$ls.get(ACCESS_TOKEN) +
          '&tp=hs&redirect=' +
          encodeURIComponent('/constructNotice?signUser=' + this.project.followPerson)
      )
      console.info(
        process.env.VUE_APP_PS_WEB_BASE_URL +
          '/' +
          'tpLogin?token=' +
          this.$ls.get(ACCESS_TOKEN) +
          '&tp=hs&redirect=' +
          encodeURIComponent('/constructNotice?signUser=' + this.project.followPerson)
      )
    },

    createQuality() {
      this.windowOpen('/workReport/addQuality/' + this.taskId)
    },

    toExecute() {
      this.windowOpen('/workReport/execute/' + this.task.projectId)
    },
    toTaskLog() {
      this.$refs.dataChangeTimeLine.open([this.taskId])
    },

    openSettlementDetail() {
      this.showSettlementDetail = true
    },
    closeSettlementDetail() {
      this.showSettlementDetail = false
    },
    fetchQualityList() {
      this.qualityRecords = []
      this.psQualityRecords = []
      this.hteQualityRecords = []
      this.fetchPsQualityList()
      // this.fetchHteQualityList()
    },
    fetchPsQualityList() {
      this.$set(this.qualityIpagination, 'poNo', this.project.busKey)
      this.$set(this.qualityIpagination, 'pageSize', 1000)
      postAction(this.urls.psQualityList, this.qualityIpagination).then((res) => {
        if (res.success) {
          this.psQualityRecords = res.result.records
          this.$set(this.qualityIpagination, 'total', res.result.total)
          this.psQualityRecords.forEach((r) => {
            if (r.status != '3' && r.status != '4') {
              r.fineAmount = ''
            }
          })
          this.qualityRecords = [...this.psQualityRecords, ...this.hteQualityRecords]
        }
      })
    },
    fetchHteQualityList() {
      this.$set(this.qualityIpagination, 'poNo', this.project.busKey)
      postAction(this.urls.hteQualityList, this.qualityIpagination).then((res) => {
        if (res.success) {
          this.hteQualityRecords = res.result
          this.qualityRecords = [...this.psQualityRecords, ...this.hteQualityRecords]
        }
      })
    },
    fetchCheckList() {
      getAction(this.urls.loadPurchaseOrder + '?purchaseOrderNumber=' + this.project.busKey).then((res) => {
        if (res.success) {
          this.checkListRecords = res.result
        }
      })
    },
    /**
     * 表结构切换页码
     */
    qualityHandleTableChange(pagination, filters, sorter) {
      this.qualityIpagination = pagination
      this.qualityIpagination.pageNo = this.qualityIpagination.current
      this.fetchQualityList()
    },
    /**
     * 表结构切换页码
     */
    checkListHandleTableChange(pagination, filters, sorter) {
      this.checnListIpagination = pagination
      this.checnListIpagination.pageNo = this.checnListIpagination.current
      this.fetchCheckList()
    },

    openUserSelector() {
      this.showUserSelector = true
    },
    selectUser(selection) {
      if (selection.length > 0) {
        this.$set(this.task, 'handlerUserId', selection[0].username.trim())
        this.$set(this.task, 'handlerUser', selection[0].realname.trim())
      }
      this.showUserSelector = false
    },
    toContractAttach() {
      this.windowOpen('/workReport/attach/' + this.project.id)
    },
    calcTaskStatus() {
      let resultA = this.task.partaResult
      let resultB = this.task.partbResult
      let taskResultMap = {}
      taskResultMap['0000'] = '0' //甲未报工，乙未报工
      taskResultMap['0010'] = '1' //甲未报工，乙报完成
      taskResultMap['0011'] = '2' //甲未报工，乙报合格
      taskResultMap['1000'] = '3' //甲报完成，乙未报工
      taskResultMap['1010'] = '4' //甲报完成，乙报完成
      taskResultMap['1011'] = '5' //甲报完成，乙报合格
      taskResultMap['1100'] = '6' //甲报合格，已未报工
      taskResultMap['1110'] = '7' //甲报合格，乙报完成
      taskResultMap['1111'] = '8' //甲报合格，乙报合格
      let resultMap = {}
      resultMap['质量不合格'] = '10'
      resultMap['质量合格'] = '11'
      let prefix = '00'
      let suffix = '00'
      if (resultMap[resultA]) {
        prefix = resultMap[resultA]
        if (prefix == '10') {
          if (this.task.partaStatus == '1') {
            prefix = '00'
          }
        }
      }
      if (resultMap[resultB]) {
        suffix = resultMap[resultB]
        if (suffix == '10') {
          if (this.task.partbStatus == '1') {
            suffix = '00'
          }
        }
      }
      let key = prefix + suffix
      let taskStatus = taskResultMap[key]
      return taskStatus
    },
  },
  watch: {
    task: {
      handler(newV, oldV) {
        this.$set(this.task, 'status', this.calcTaskStatus())
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';

.page-main {
  .container {
    .content {
      margin-top: 20px;

      section {
        .section-table {
          .add-btn {
            margin-left: 0;
            margin-bottom: 10px;
          }
        }
      }
    }
  }

  .tips-box {
    margin-top: 32px;

    .add-btn {
      width: 180px;
      height: 40px;
      line-height: 40px;
      background-color: #4095e4;
      border-radius: 2px;
    }
  }
}

.icon-file {
  background-image: url('~@assets/file.png');
}

.cr-content-pop {
  p {
    margin-bottom: 15px;
    color: #666;

    &:last-child {
      margin-bottom: 0;
    }
  }
}
</style>
